﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using System;
using UnityEngine.AI;

public enum WashState
{
    None,       //默认
    Ready,      //准备好清洗
    Soap,       //抹肥皂
    Clean,      //清洗
    WipeAndDry,  //擦干\
    Finish,     //完成
}

public enum eAnimLediClean
{
    idell_p,    //待机状态
    move_a,     
    takeoff_p,  //起飞
    fly_at,     //正在飞行
    fly_run_a_o,

    talk1_a_1,  //
    talk1_a_2,
    talk1_a_3,

    talk2_a_1,
    talk2_a_2,
    talk2_a_3,

    enjoy_a_1,  
    enjoy_a_2,
    enjoy_a_3,

    all_talk_01,
    all_talk_02,
    all_talk_03,

    a_o_t_p,    //蛋形(空中)->人形
    p_t_a_o,     //人形-》蛋形（空中）
    p_t_a_wheel, //蛋形-》蛋形（轮子）
    a_t_p_wheel, //蛋形(轮子）-》蛋形

    sheke_body_a,

}

public class WashBodyGame : BaseToyBoxGame
{

    private const string ASSET_PATH = "game_toybox/WashBodyGameRoot";

    private Vector3 centerPoint = new Vector3(0, -5.388832f,0);

    private Transform lediPos;

    private int seq_timer;

    private GameAudioSource currentAudioSrc;

    PoolObjHandle<ActorRoot> actor;

    private Transform m_player;

    private RuntimeAnimatorController startRuntimeAnimator;

    public AnimatorEx animatorEx;

    private bool m_isTotalTimerStart = false;

    private bool m_isWarningTimerStart = false;

    private float m_timer;

    private float movespeed = 30f;

    public override void OnStart(System.Action<bool> callback)
    {
        base.OnStart(callback);

        Debug.Log("--------------- WashGame OnStart!");

        CreateGameRoot();

        AddEventListener();

        actor = ActorObjManager.Instance.GetActor(ActorNames.LeDi);
        actor.handle.TurnFront(()=> {
            m_player = actor.handle.MyTransform;
            m_player.GetComponent<NavMeshAgent>().enabled = false;

            startRuntimeAnimator = actor.handle.AnimatorController.Animator.runtimeAnimatorController;
            animatorEx = new AnimatorEx(actor.handle.gameObject);
            actor.handle.ChangeAnimatorController(WashResController.Instance.m_lediCleanAnimator);

            //切换动作时，可能出现嘴巴和眼睛blendshape的问题，所以在播放之前重置一下
            WashResController.Instance.ResetLediBlendShape();
            TimerManager.Instance.AddTimer(.2f, () => {

                animatorEx.PlaySequence(eAnimLediClean.all_talk_01.ToString(), WashResController.Instance.GetAudioPath(WashResController.audio_qingjie), () =>
                {
                    Vector3 moveDir = (centerPoint - m_player.position).normalized;
                    m_player.DOLookAt(moveDir, .5f, AxisConstraint.Y);

                    animatorEx.PlayDelay(eAnimLediClean.p_t_a_wheel.ToString(), .2f).OnFinished(() =>
                    {
                        float distance = Vector3.Distance(m_player.position, centerPoint);
                        m_player.DOMove(centerPoint, distance / movespeed).OnComplete(() =>
                        {
                            actor.handle.TurnFront(() =>
                            {
                                WindowManager.Instance.OpenWindow(WinNames.LediCleanPanel);
                                RestartTimer();
                                WashController.Instance.ChangeState(WashState.Soap);
                            });
                        });
                    });
                });


            });
        });
       
    }

    private void AddEventListener()
    {
        EventBus.Instance.AddEventHandler(EventID.GAME_PAUSE, OnGamePause);
        EventBus.Instance.AddEventHandler(EventID.RESET_TIMER, RestartTimer);
        FEasyInput.AddEvent(EEasyInputType.OnUp, RestartTimer);
        FEasyInput.AddEvent(EEasyInputType.OnHover, RestartTimer);
        WashController.Instance.washGameFinishedEvent = () => { OnGameComplete(true); };
    }

    private void RemoveListener()
    {
        EventBus.Instance.RemoveEventHandler(EventID.GAME_PAUSE, OnGamePause);
        EventBus.Instance.RemoveEventHandler(EventID.RESET_TIMER, RestartTimer);
        FEasyInput.RemoveEvent(EEasyInputType.OnUp, RestartTimer);
        FEasyInput.RemoveEvent(EEasyInputType.OnHover, RestartTimer);
        WashController.Instance.washGameFinishedEvent = null;
    }

    public override void OnUpdate()
    {
        base.OnUpdate();

        if (animatorEx != null)
            animatorEx.OnUpdate();

        if (m_isWarningTimerStart)
        {
            m_timer += Time.deltaTime;
            if (m_timer > 7 && !m_isTotalTimerStart)
            {
                m_timer = 0;
                animatorEx.PlaySequence(eAnimLediClean.talk2_a_1.ToString(), WashResController.Instance.GetAudioPath(WashResController.audio_kuaidian));
                m_isTotalTimerStart = true;
            }
            else if(m_timer > 10)
            {
                m_timer = 0;

                WashResController.Instance.CloseAllDragItemInteractive();

                animatorEx.PlaySequence(eAnimLediClean.talk1_a_1.ToString(), WashResController.Instance.GetAudioPath(WashResController.audio_xiaci),()=>
                {
                    ExitGameAnimation();
                });
            }
        }

        if (Input.GetKeyDown(KeyCode.G))
        {
            OnGameComplete(true);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            OnStart(null);
        }
    }

    public void ExitGameAnimation()
    {
        StopTimer();
        animatorEx.Play(eAnimLediClean.a_t_p_wheel.ToString()).OnFinished(() =>
        {
            TimerManager.Instance.AddTimer(.1f, () => { OnGameComplete(true); });
        });
    }

    private void CreateGameRoot()
    {
        WashResController.CreateInstance();
        WashController.Instance._washbodyGame = this;
        WashController.Instance.transform.SetParent(toyboxGameRoot);
        WashController.Instance.transform.ResetTransformForLocal();
    }

    private void StopTimer()
    {
        m_timer = 0;
        m_isWarningTimerStart = false;
        m_isTotalTimerStart = false;
    }

    private void RestartTimer()
    {
        m_timer = 0;
        m_isWarningTimerStart = true;
        m_isTotalTimerStart = false;
    }

    private void OnGamePause()
    {
        //OnGameComplete(true);
    }

    private void OnGameResume()
    {

    }

    public override void OnExit()
    {
        base.OnExit();

        m_player.GetComponent<NavMeshAgent>().enabled = true;
        WashResController.Instance.SetWaterDropProgress(0);

        TimerManager.Instance.RemoveAllTimer();
        WashResController.DestroyInstance();
        WashController.DestroyInstance();
        actor.handle.ChangeAnimatorController(startRuntimeAnimator);
        WindowManager.Instance.CloseWindow(WinNames.LediCleanPanel);
        RemoveListener();

    }


}
